<template>
  <view class="u-upload" :style="[addStyle(customStyle)]">
    <view class="u-upload__wrap">
      <template v-if="previewImage">
        <view class="u-upload__wrap__preview" v-for="(item, index) in lists" :key="index">
          <image
            v-if="item.isImage || (item.type && item.type === 'image')"
            :src="item.thumb || item.url"
            :mode="imageMode"
            class="u-upload__wrap__preview__image"
            @tap="onPreviewImage(item)"
          />
          <view v-else class="u-upload__wrap__preview__other">
            <u-icon
              color="#80CBF9"
              size="52"
              :name="item.isVideo || (item.type && item.type === 'video') ? 'camera-fill' : 'file-text'"
            />
            <text class="u-upload__wrap__preview__other__text">{{item.isVideo || (item.type && item.type === 'video') ? '视频' : '文件'}}</text>
          </view>
          <view
            class="u-upload__status"
            v-if="item.status === 'uploading' || item.status === 'failed'"
          >
            <view class="u-upload__status__icon">
              <u-icon
                v-if="item.status === 'failed'"
                name="close-circle"
                color="#ffffff"
                size="50"
              />
              <u-loading-page
                size="44"
                mode="circle"
                color="#ffffff"
                v-else
              />
            </view>
            <text v-if="item.message" class="u-upload__status__message">{{ item.message }}</text>
          </view>
          <view
            class="u-upload__deletable"
            v-if="item.status !== 'uploading' && (deletable || item.deletable) && !disabled"
            @tap.stop="deleteItem(index)"
          >
            <view class="u-upload__deletable__icon">
              <u-icon name="close" color="#ffffff" size="24"/>
            </view>
          </view>
          <view class="u-upload__success" v-if="item.status === 'success'">
            <view class="u-upload__success__icon">
              <u-icon name="checkmark" color="#ffffff" size="30"/>
            </view>
          </view>
        </view>
      </template>
      <template v-if="isInCount && !disabled">
        <view v-if="$slots.default || $slots.$default" @tap="chooseFile">
          <slot></slot>
        </view>
        <view
          v-else
          class="u-upload__button"
          :hover-class="!disabled ? 'u-upload__button--hover' : ''"
          hover-stay-time="150"
          @tap="chooseFile"
          :class="[disabled && 'u-upload__button--disabled']"
        >
          <u-icon :name="uploadIcon" size="52" :color="uploadIconColor" />
          <text v-if="uploadText" class="u-upload__button__text">{{ uploadText }}</text>
        </view>
      </template>
    </view>
  </view>
</template>

<script>
import props from './props';
import mpMixin from '../../../mixin/mpMixin';
import { commonUtils } from '../../../utils/common';
import { chooseFile } from './utils';
import { isArray, isFunction, isPromise } from '../../../utils/verify';

export default {
  name: 'uni-upload',
  mixins: [mpMixin, props],
  data() {
    return {
      addStyle: commonUtils.addStyle,
      addUnit: commonUtils.addUnit,
      lists: [],
      isInCount: true
    }
  },
  watch: {
    accept: {
      handler(val) {
        // #ifndef MP-WEIXIN
        if (val === 'all' || val === 'media') {
          commonUtils.error('只有微信小程序才支持把accept配置为all、media之一')
        }
        // #endif
        // #ifndef H5 || MP-WEIXIN
        if (val === 'file') {
          commonUtils.error('只有微信小程序和H5(HX2.9.9)才支持把accept配置为file')
        }
        // #endif
      },
      immediate: true
    },
    // 监听文件列表的变化，重新整理内部数据
    fileList: {
      handler() {
        this.formatFileList()
      },
      immediate: true
    }
  },
  methods: {
    formatFileList() {
      const {
        fileList = [], maxCount
      } = this;
      const lists = fileList.map((item) =>
        Object.assign(Object.assign({}, item), {
          // 如果item.url为本地选择的blob文件的话，无法判断其为video还是image，此处优先通过accept做判断处理
          isImage: this.accept === 'image' || this.isImageFile(item.url || item.thumb),
          isVideo: this.accept === 'video' || this.isVideoFile(item.url || item.thumb),
          deletable: typeof item.deletable === 'boolean' ? item.deletable : this.deletable
        })
      );
      this.lists = lists
      this.isInCount = lists.length < maxCount
    },
    chooseFile() {
      const { disabled, maxCount, multiple, lists } = this;
      if (disabled) return;
      let capture;
      try {
        capture = isArray(this.capture) ? this.capture : this.capture.split(',');
      } catch (e) {
        capture = []
      }
      const data = Object.assign({
        accept: this.accept,
        multiple: this.multiple,
        capture: capture,
        compressed: this.compressed,
        maxDuration: this.maxDuration,
        sizeType: this.sizeType,
        camera: this.camera
      }, {
        maxCount: maxCount - lists.length
      })
      chooseFile(data).then(res => {
        this.onBeforeRead(multiple ? res : res[0]);
      }).catch(err => {
        this.$emit('error', err)
      })
    },
    onBeforeRead(file) {
      const { beforeRead, useBeforeRead } = this;
      let res = true
      if (isFunction(beforeRead)) {
        res = beforeRead(file, this.getDetail());
      }
      if (useBeforeRead) {
        res = new Promise((resolve, reject) => {
          this.$emit(
            'beforeRead',
            Object.assign(Object.assign({
              file
            }, this.getDetail()), {
              callback: (ok) => {
                // eslint-disable-next-line
                ok ? resolve() : reject();
              }
            })
          );
        });
      }
      if (!res) {
        return;
      }
      if (isPromise(res)) {
        res.then((data) => this.onAfterRead(data || file));
      } else {
        this.onAfterRead(file);
      }
    },
    getDetail(index) {
      return {
        name: this.name,
        index: index == null ? this.fileList.length : index
      };
    },
    onAfterRead(file) {
      const { maxSize, afterRead } = this;
      const oversize = Array.isArray(file) ? file.some((item) => item.size > maxSize) : file.size > maxSize;
      if (oversize) {
        this.$emit('oversize', Object.assign({
          file
        }, this.getDetail()));
        return;
      }
      if (typeof afterRead === 'function') {
        afterRead(file, this.getDetail());
      }
      this.$emit('afterRead', Object.assign({
        file
      }, this.getDetail()));
    },
    deleteItem(index) {
      this.$emit(
        'remove',
        Object.assign(Object.assign({}, this.getDetail(index)), {
          file: this.fileList[index]
        })
      );
    },
    // 预览图片
    onPreviewImage(item) {
      if (!item.isImage || !this.preview) return
      uni.previewImage({
        // 先filter找出为图片的item，再返回filter结果中的图片url
        urls: this.lists.filter((item) => this.accept === 'image' || uni.$u.test.image(item.url || item.thumb)).map((item) => item.url || item.thumb),
        current: item.url || item.thumb,
        fail() {
          commonUtils.toast('图片预览失败')
        }
      })
    },
    onPreviewVideo(event) {
      if (!this.data.preview) return;
      const { index } = event.currentTarget.dataset;
      const { lists } = this.data;
      wx.previewMedia({
        sources: lists
          .filter((item) => this.isVideoFile(item))
          .map((item) =>
            Object.assign(Object.assign({}, item), {
              type: 'video'
            })
          ),
        current: index,
        fail() {
          commonUtils.toast('视频预览失败')
        }
      });
    },
    onClickPreview(event) {
      const { index } = event.currentTarget.dataset;
      const item = this.data.lists[index];
      this.$emit('preview', Object.assign(Object.assign({}, item), this.getDetail(index)));
    },
    isImageFile(value) {
      const newValue = value.split('?')[0]
      const IMAGE_REGEXP = /\.(jpeg|jpg|gif|png|svg|webp|jfif|bmp|dpg)/i
      return IMAGE_REGEXP.test(newValue)
    },
    isVideoFile(value) {
      const VIDEO_REGEXP = /\.(mp4|mpg|mpeg|dat|asf|avi|rm|rmvb|mov|wmv|flv|mkv|m3u8)/i
      return VIDEO_REGEXP.test(value)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../../../style/components";
$u-upload-preview-border-radius: 4rpx !default;
$u-upload-preview-margin: 0 16rpx 16rpx 0 !default;
$u-upload-image-width: 120rpx !default;
$u-upload-image-height: $u-upload-image-width;
$u-upload-other-bgColor: rgb(242, 242, 242) !default;
$u-upload-other-flex: 1 !default;
$u-upload-text-font-size: 22rpx !default;
$u-upload-text-color: $u-tips-color !default;
$u-upload-text-margin-top: 4rpx !default;
$u-upload-deletable-right: 0 !default;
$u-upload-deletable-top: 0 !default;
$u-upload-deletable-bgColor: rgb(55, 55, 55) !default;
$u-upload-deletable-height: 28rpx !default;
$u-upload-deletable-width: $u-upload-deletable-height;
$u-upload-deletable-boder-bottom-left-radius: 200rpx !default;
$u-upload-deletable-zIndex: 3 !default;
$u-upload-success-bottom: 0 !default;
$u-upload-success-right: 0 !default;
$u-upload-success-border-style: solid !default;
$u-upload-success-border-top-color: transparent !default;
$u-upload-success-border-left-color: transparent !default;
$u-upload-success-border-bottom-color: $u-success !default;
$u-upload-success-border-right-color: $u-upload-success-border-bottom-color;
$u-upload-success-border-width: 18rpx !default;
$u-upload-icon-top: 0 !default;
$u-upload-icon-right: 0 !default;
$u-upload-icon-h5-top: 2rpx !default;
$u-upload-icon-h5-right: 0 !default;
$u-upload-icon-width: 34rpx !default;
$u-upload-icon-height: $u-upload-icon-width;
$u-upload-success-icon-bottom: -24rpx !default;
$u-upload-success-icon-right: -20rpx !default;
$u-upload-status-right: 0 !default;
$u-upload-status-left: 0 !default;
$u-upload-status-bottom: 0 !default;
$u-upload-status-top: 0 !default;
$u-upload-status-bgColor: rgba(0, 0, 0, 0.5) !default;
$u-upload-status-icon-Zindex: 1 !default;
$u-upload-message-font-size: 24rpx !default;
$u-upload-message-color: #FFFFFF !default;
$u-upload-message-margin-top: 10rpx !default;
$u-upload-button-width: 140rpx !default;
$u-upload-button-height: $u-upload-button-width;
$u-upload-button-bgColor: rgb(244, 245, 247) !default;
$u-upload-button-border-radius: 4rpx !default;
$u-upload-botton-margin: 0 16rpx 16rpx 0 !default;
$u-upload-text-font-size: 22rpx !default;
$u-upload-text-color: $u-tips-color !default;
$u-upload-text-margin-top: 4rpx !default;
$u-upload-hover-bgColor: rgb(230, 231, 233) !default;
$u-upload-disabled-opacity: .5 !default;

.u-upload {
  @include flex(column);
  flex: 1;

  &__wrap {
    @include flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    flex: 1;

    &__preview {
      border-radius: $u-upload-preview-border-radius;
      margin: $u-upload-preview-margin;
      position: relative;
      overflow: hidden;
      @include flex;

      &__image {
        width: $u-upload-image-width;
        height: $u-upload-image-width;
      }

      &__other {
        width: $u-upload-image-width;
        height: $u-upload-image-height;
        background-color: $u-upload-other-bgColor;
        flex: $u-upload-other-flex;
        @include flex(column);
        justify-content: center;
        align-items: center;

        &__text {
          font-size: $u-upload-text-font-size;
          color: $u-upload-text-color;
          margin-top: $u-upload-text-margin-top;
        }
      }
    }
  }

  &__deletable {
    position: absolute;
    top: $u-upload-deletable-top;
    right: $u-upload-deletable-right;
    background-color: $u-upload-deletable-bgColor;
    height: $u-upload-deletable-height;
    width: $u-upload-deletable-width;
    @include flex;
    border-bottom-left-radius: $u-upload-deletable-boder-bottom-left-radius;
    align-items: center;
    justify-content: center;
    z-index: $u-upload-deletable-zIndex;

    &__icon {
      position: absolute;
      transform: scale(0.7);
      top: $u-upload-icon-top;
      right: $u-upload-icon-right;
      /* #ifdef H5 */
      top: $u-upload-icon-h5-top;
      right: $u-upload-icon-h5-right;
      /* #endif */
    }
  }

  &__success {
    position: absolute;
    bottom: $u-upload-success-bottom;
    right: $u-upload-success-right;
    @include flex;
    // 由于weex(nvue)为阿里巴巴的KPI(部门业绩考核)的laji产物，不支持css绘制三角形
    // 所以在nvue下使用图片，非nvue下使用css实现
    /* #ifndef APP-NVUE */
    border-style: $u-upload-success-border-style;
    border-top-color: $u-upload-success-border-top-color;
    border-left-color: $u-upload-success-border-left-color;
    border-bottom-color: $u-upload-success-border-bottom-color;
    border-right-color: $u-upload-success-border-right-color;
    border-width: $u-upload-success-border-width;
    align-items: center;
    justify-content: center;
    /* #endif */

    &__icon {
      /* #ifndef APP-NVUE */
      position: absolute;
      transform: scale(0.7);
      bottom: $u-upload-success-icon-bottom;
      right: $u-upload-success-icon-right;
      /* #endif */
      /* #ifdef APP-NVUE */
      width: $u-upload-icon-width;
      height: $u-upload-icon-height;
      /* #endif */
    }
  }

  &__status {
    position: absolute;
    top: $u-upload-status-top;
    bottom: $u-upload-status-bottom;
    left: $u-upload-status-left;
    right: $u-upload-status-right;
    background-color: $u-upload-status-bgColor;
    @include flex(column);
    align-items: center;
    justify-content: center;

    &__icon {
      position: relative;
      z-index: $u-upload-status-icon-Zindex;
    }

    &__message {
      font-size: $u-upload-message-font-size;
      color: $u-upload-message-color;
      margin-top: $u-upload-message-margin-top;
    }
  }

  &__button {
    @include flex(column);
    align-items: center;
    justify-content: center;
    width: $u-upload-button-width;
    height: $u-upload-button-height;
    background-color: $u-upload-button-bgColor;
    border-radius: $u-upload-button-border-radius;
    margin: $u-upload-botton-margin;
    /* #ifndef APP-NVUE */
    box-sizing: border-box;
    /* #endif */

    &__text {
      font-size: $u-upload-text-font-size;
      color: $u-upload-text-color;
      margin-top: $u-upload-text-margin-top;
    }

    &--hover {
      background-color: $u-upload-hover-bgColor;
    }

    &--disabled {
      opacity: $u-upload-disabled-opacity;
    }
  }
}
</style>
